<?php
namespace app\beautiful\controller\admin;
use app\beautiful\logic\LogsLogic;
use app\beautiful\model\CouponModel;
use app\beautiful\model\LevelModel;
use app\beautiful\model\member\MemberBalanceModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberIntegralModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\order\CashierOrderModel;
use app\beautiful\model\setting\SettingBalanceModel;
use app\beautiful\model\StaffMemberModel;
use app\beautiful\model\StaffModel;
use app\BaseController;
use app\common\logic\DataLogic;
use app\beautiful\logic\MemberWalletLogic;
use app\beautiful\logic\PartnerLogic;
use app\beautiful\model\member\MemberOnceCardModel;
use think\facade\Db;

class Member extends BaseController{
    protected $name='会员';

    public function index()
    {
        $nick_name=$this->request->param('nick_name');
        $mobile=$this->request->param('mobile');
        $level_id=$this->request->param('level_id/d',-99);
        $birthday_type=$this->request->param('birthday_type/d',1);
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
        ];
        if(!empty($nick_name))  $where[]=['nick_name','=',$nick_name];

        if(!empty($mobile))  $where[]=['mobile','=',$mobile];

        if($level_id!=-99)  $where[]=['level_id','=',$level_id];

        if(in_array($birthday_type,[2,3])){
            if($birthday_type==2)   $month=date("m");
            if($birthday_type==3)   $month=date("m",strtotime("+1 month"));
            $where[]=['birthday_month','=',$month];
        }

        $memberModel=new MemberModel();
        $memberModel=$memberModel->with(['level'=>function($query){
            $query->field('level_id,name');
        }]);
        $order=['add_time'=>'desc'];
        $append=['birthday'];
        $field='member_id,nick_name,face,mobile,birthday_year,birthday_month,birthday_day';
        $data=DataLogic::getDataList($memberModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        $level=LevelModel::where([['shop_id','=',$this->request->shopId],['is_delete','=',0]])->field('level_id,name')->select()->toArray();
   
        //处理数据
        $lists=$data['list'];
        if(empty(!$lists)){                 
            $memberIds = $balances = $integrals = [];
            foreach($lists as $val){
                $memberIds[$val['member_id']] = $val['member_id'];
            }
            if(!empty($memberIds)){
               $MemberBalanceModel = new MemberBalanceModel();
               $balances =  $MemberBalanceModel->getBalanceSumByMemberId($memberIds);
               $MemberIntegralModel = new MemberIntegralModel();
               $integrals = $MemberIntegralModel->getIntegralSumByMemberId($memberIds);
            }
            foreach ($lists as $k => $list){
                $lists[$k]['balance']=$balances[$list['member_id']] ?? 0;
                $lists[$k]['integral']=$integrals[$list['member_id']] ?? 0;;
            }
        }
        $data['list']=$lists;
        $data['level']=$level;
        return $this->success($data);
    }

    public function show()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');
        if($member->is_delete != 0)  return $this->error($this->name.'不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        $balance = MemberBalanceModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
                ['valid_bg_time','<=',$this->request->time()]
            ])->sum('remain_balance') ?? 0;

        $integral = MemberIntegralModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
                ['expire_time','>',$this->request->time()]
            ])->sum('remain_integral') ?? 0;

        $detail=[
            'balance'=>$balance,
            'integral'=>$integral,
        ];
        return $this->success(['detail'=>$detail]);
    }

    public function save()
    {
        $nick_name=$this->request->param('nick_name');
        $mobile=$this->request->param('mobile');
        $birthday=$this->request->param('birthday');
        if(empty($nick_name)){
            return $this->error('请填写昵称');
        }
        if(empty($mobile) || !is_mobile($mobile)){
            return $this->error('请填写正确的手机号');
        }
        if(empty($birthday)){
            return $this->error('请选择生日');
        }
        if(false === $birthday_unix=strtotime($birthday)){
            return $this->error('请选择正确的生日');
        }
        $birthday_arr=explode('-',$birthday);
        $birthday_year=$birthday_arr[0];
        $birthday_month=$birthday_arr[1];
        $birthday_day=$birthday_arr[2];

        if(null !== MemberModel::where([
                ['shop_id','=',$this->request->shopId],
                ['is_delete','=',0],
                ['mobile','=',$mobile]
            ])->find()){
            return $this->error('该手机号已注册');
        }

        $member= new MemberModel();
        $member->shop_id=$this->request->shopId;
        $member->nick_name=$nick_name;
        $member->mobile=$mobile;
        $member->birthday_year=$birthday_year;
        $member->birthday_month=$birthday_month;
        $member->birthday_day=$birthday_day;
        $rst = $member->save();
        if($rst) {
            $partnerLogic = new PartnerLogic($this->request->shopId);
            $partnerLogic->memberPartner($mobile,$nick_name);
        }
        $return=[
            'member'=>[
                'member_id'=>$member->member_id,
                'nick_name'=>$member->nick_name,
                'mobile'=>$member->mobile,
            ]
        ];
        
        return $this->success($return);

    }

    public function export()
    {

        $nick_name=$this->request->param('nick_name');
        $mobile=$this->request->param('mobile');
        $level_id=$this->request->param('level_id/d',-99);
        $birthday_type=$this->request->param('birthday_type/d',1);
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
        ];
        if(!empty($nick_name))  $where[]=['nick_name','=',$nick_name];

        if(!empty($mobile))  $where[]=['mobile','=',$mobile];

        if($level_id!=-99)  $where[]=['level_id','=',$level_id];

        if(in_array($birthday_type,[2,3])){
            if($birthday_type==2)   $month=date("m");
            if($birthday_type==3)   $month=date("m",strtotime("+1 month"));
            $where[]=['birthday_month','=',$month];
        }

        $memberModel=new MemberModel();
        $memberModel=$memberModel->with(['level'=>function($query){
            $query->field('level_id,name');
        }]);
        $order=['add_time'=>'desc'];
        $append=['birthday'];
        $field='member_id,nick_name,face,mobile,birthday_year,birthday_month,birthday_day';
        $data= $list=$memberModel->where($where)
            ->field($field)->order($order)
            ->limit(200)->page($this->request->page)
            ->select()
            ->append($append)
            ->toArray();

        //处理数据
        $csvArr=[];
        if(empty(!$data)){
            $memberIds = $balances = $integrals = [];
            foreach($data as $val){
                $memberIds[$val['member_id']] = $val['member_id'];
            }
            if(!empty($memberIds)){
                $MemberBalanceModel = new MemberBalanceModel();
                $balances =  $MemberBalanceModel->getBalanceSumByMemberId($memberIds);
                $MemberIntegralModel = new MemberIntegralModel();
                $integrals = $MemberIntegralModel->getIntegralSumByMemberId($memberIds);
            }
            foreach ($data as $k => $list){
                $csvArr[]=[
                    $list['nick_name'],
                    $list['mobile'],
                    isset($list['level']) ? $list['level']['name'] : '普通会员',
                    $balances[$list['member_id']] ?? 0,
                    $integrals[$list['member_id']] ?? 0
                ];
            }
        }

        $this->download_send_headers("data_export_" . date("Y-m-d") . ".csv");
        $head=array('会员昵称','会员手机号','会员等级','会员余额','会员积分');
        echo $this->array2csv($csvArr,$head);
        unset($csvArr);
        die();

    }

    protected  function array2csv(array &$array,$head)

    {

        if (count($array) == 0) {

            return null;

        }

        ob_start();

        $df = fopen("php://output", 'w');

        if(!$head){

            $head=array_keys(reset($array));

        }

        fputcsv($df,$head);

        foreach ($array as $row) {

            fputcsv($df, $row);

        }

        fclose($df);

        return ob_get_clean();

    }

    protected function download_send_headers($filename)
    {
        // disable caching

        $now = gmdate("D, d M Y H:i:s");

        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");

        header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");

        header("Last-Modified: {$now} GMT");

        // force download

        header("Content-Type: application/force-download");

        header("Content-Type: application/octet-stream");

        header("Content-Type: application/download");

        // disposition / encoding on response body

        header("Content-Disposition: attachment;filename={$filename}");

        header("Content-Transfer-Encoding: binary");
    }

    public function saveNickName()
    {
        $member_id=$this->request->param('member_id/d',0);
        $nick_name=$this->request->param('nick_name');
        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');
        if($member->is_delete != 0)  return $this->error($this->name.'不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        if(empty($nick_name)) return $this->error('请输入会员昵称');

        $member->nick_name=$nick_name;
        $member->save();
        return $this->success('修改成功');
    }

    /****************************************************** --start--会员详情--start--*********************************************************************/

    public function detail()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)){
            return $this->error($this->name.'不存在');
        }
        if($member->is_delete != 0){
            return $this->error($this->name.'不存在');
        }
        if($member->shop_id != $this->request->shopId){
            return $this->error($this->name.'不存在');
        }
        $member->append(['birthday']);

        $once_card_num=MemberOnceCardModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
            ])->count() ?? 0;

        $balance = MemberBalanceModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
            ])->sum('remain_balance') ?? 0;

        $use_balance = MemberBalanceModel::where([
            ['shop_id','=',$this->request->shopId],
            ['member_id','=',$member_id],
            ['valid_bg_time','<=',$this->request->time()]
        ])->sum('remain_balance') ?? 0;

        $frozen_balance = MemberBalanceModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
                ['valid_bg_time','>',$this->request->time()]
            ])->sum('remain_balance') ?? 0;

        $integral = MemberIntegralModel::where([
            ['shop_id','=',$this->request->shopId],
            ['member_id','=',$member_id],
            ['expire_time','>',$this->request->time()]
        ])->sum('remain_integral') ?? 0;

        $coupon_count = MemberCouponModel::where([
            ['shop_id','=',$this->request->shopId],
            ['member_id','=',$member_id],
        ])->count() ?? 0;

        $detail=[
            'nick_name'=>$member->nick_name,
            'level_name'=>$member->level ? $member->level->name : '普通会员',
            'mobile'=>$member->mobile,
            'face'=>$member->face,
//            'adviser'=>$member->adviser ? $member->adviser->staff->name : '暂无',
//            'staff_id'=>$member->adviser ? $member->adviser->staff->staff_id : 0,
            'once_card_num'=>$once_card_num,
            'balance'=>$balance,
            'use_balance'=>$use_balance,
            'frozen_balance'=>$frozen_balance,
            'integral'=>$integral,
            'coupon_count'=>$coupon_count,
        ];
        return $this->success(['detail'=>$detail]);
    }


    public function assignAdviser()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');
        if($member->is_delete != 0)  return $this->error($this->name.'不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        $staff_id = $this->request->param('staff_id/d',0);
        if(null === $staff = StaffModel::find($staff_id)) return $this->error('顾问不存在');
        if($staff->is_delete != 0)  return $this->error('顾问不存在');
        if($staff->shop_id != $this->request->shopId)   return $this->error('顾问不存在');
        if($staff->adviser_jurisdiction!=1) return $this->error('顾问不存在');
        if($staff->status != 1) return $this->error('顾问已离职');

        if(null !== $staffMember = StaffMemberModel::where([
                ['shop_id','=',$this->request->shopId],
                ['member_id','=',$member_id],
            ])->find()){
            if($staffMember->staff_id == $staff_id)   return $this->error('这个顾问本来就是这个会员的顾问');
        }else{
            $staffMember = new StaffMemberModel();
            $staffMember->shop_id = $this->request->shopId;
            $staffMember->member_id = $member_id;
        }
        $staffMember->staff_id = $staff_id;
        $staffMember->save();
        return $this->success('操作成功');

    }

    public function balanceRecharge()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');
        if($member->is_delete != 0)  return $this->error($this->name.'不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        $balance= $this->request->param('balance/f',0);
        $give_balance =$this->request->param('give_balance/f',0);
        if($balance <=0 ) return $this->error('请填写充值金额，且金额不能小于等于0');
        if($give_balance < 0) return $this->error('请填写赠送金额，金额不能小于0');

        $balance_setting=SettingBalanceModel::where([['shop_id','=',$this->request->shopId]])->find();
        $frozen_days=$balance_setting->is_frozen_give_money ==1 ? $balance_setting->frozen_days : 0;

        Db::startTrans();
        try{
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
            $res = $MemberWalletLogic->addBalance($balance, $give_balance, 3,'', $this->request->accountId);
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function balanceDeduction()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');
        if($member->is_delete != 0)  return $this->error($this->name.'不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        $balance= $this->request->param('balance/f',0);
        $original_deduction =$this->request->param('original_deduction/f',0);
        if($balance <=0 ) return $this->error('请填写扣除金额，且金额不能小于等于0');
        if($original_deduction <= 0) return $this->error('请填写原本扣除金额，金额不能小于等于0');
        if($original_deduction < $balance) return $this->error('原本扣除的金额不能小于实际扣除的金额');

        $remarks=$this->request->param('remarks');

        Db::startTrans();
        try{
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);
            $res = $MemberWalletLogic->useBalance($balance, $original_deduction, 7, $remarks, $this->request->accountId);
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }

    }

    public function integralRecharge()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');
        if($member->is_delete != 0)  return $this->error($this->name.'不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        $integral= $this->request->param('integral/d',0);
        if($integral <=0 ) return $this->error('请填写充值积分，且积分不能小于等于0');

       

        Db::startTrans();
        try{
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId,$member_id);
            $res = $MemberWalletLogic->addIntegal($integral, 2, '', $this->request->accountId);
            if(!$res){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function integralDeduction()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');
        if($member->is_delete != 0)  return $this->error($this->name.'不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        $integral= $this->request->param('integral/d',0);
        if($integral <=0 ) return $this->error('请填写积分，且积分不能小于等于0');

        $remarks=$this->request->param('remarks');


        Db::startTrans();
        try{
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId,$member_id);
            $res = $MemberWalletLogic->useIntegral($integral, 5,$remarks, $this->request->accountId);
            if(!$res){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            Db::commit();
            return $this->success('操作成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function sendCoupon()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');
        if($member->is_delete != 0)  return $this->error($this->name.'不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        $coupon_ids = $this->request->param('coupon_ids/a',[]);
        if(empty($coupon_ids)) return $this->error('请选择优惠券');
        $coupon_data=CouponModel::where([
            ['coupon_id','in',$coupon_ids],
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['status','=',1],
            ['end_time','>=',date("Y-m-d",$this->request->time())]
        ])->field('coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit,add_time')
            ->select()->toArray();
        if(empty($coupon_data)) return $this->error('请选择优惠券');



        foreach ($coupon_data as $k => $coupon){
            $member_coupon_model = new MemberCouponModel();
            $member_coupon_data=[
                'shop_id'=>$this->request->shopId,
                'member_id'=>$member_id,
                'type_id'=>2,
                'coupon_id'=>$coupon['coupon_id'],
                'name'=>$coupon['name'],
                'coupon_money'=>$coupon['coupon_money'],
                'money_limit'=>$coupon['money_limit'],
                'valid_bg_time'=>$coupon['valid_bg_time'],
                'valid_end_time'=>$coupon['valid_end_time'],
            ];
            $member_coupon_model->save($member_coupon_data);

            LogsLogic::coupon($this->request->shopId,$member_id,1,3,$member_coupon_model->member_coupon_id,'',$this->request->accountId);
        }

        return $this->success('送券成功');
    }

    /****************************************************** --end--会员详情--end--*********************************************************************/


    /****************************************************** --start--会员详情优惠券--start--*********************************************************************/

    public function writeOffCoupon()
    {
        $member_id=$this->request->param('member_id/d',0);
        if(null === $member = MemberModel::find($member_id)) return $this->error($this->name.'不存在');
        if($member->is_delete != 0)  return $this->error($this->name.'不存在');
        if($member->shop_id != $this->request->shopId)   return $this->error($this->name.'不存在');

        $member_coupon_id =$this->request->param('member_coupon_id/d',0);
        if(null === $memberCoupon = MemberCouponModel::find($member_coupon_id)) return $this->error('优惠券不存在');
        if($memberCoupon->shop_id != $this->request->shopId) return $this->error('优惠券不存在');
        if($memberCoupon->member_id != $member_id) return $this->error('优惠券不存在');
        if($memberCoupon->status != 0) return $this->error('该优惠券已使用过了');
        if($memberCoupon->valid_end_time <date("Y-m-d")) return $this->error('该优惠券已过期');

        $memberCoupon->status=1;
        $memberCoupon->save();

        LogsLogic::coupon($this->request->shopId,$member_id,-1,7,$member_coupon_id,'',$this->request->accountId);
        return $this->success('核销成功');
    }

    /****************************************************** --end--会员详情优惠券--end--*********************************************************************/

    public function getOrderList()
    {

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
        ];

        if(!empty($order_id)) $where[]=['order_id','=',$order_id];
        if(!empty($order_type)) $where[]=['order_type','=',$order_type];
        if(!empty($status)) $where[]=['status','=',$status];

        $order_model=new CashierOrderModel();
        $order_model=$order_model->with(['skus','member']);

        $order=['add_time'=>'desc'];
        $field="*";
        $append=['add_time_format','pay_time_format','status_means','pay_type_mean'];

        $return = DataLogic::getDataList($order_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);
    }

}
